const BaseController = require("./base");
const NotFoundException = require("../exception/not_found");

function toInt(str) {
  if (typeof str === "number") return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class UserController extends BaseController {
  async getUserByRole() {
    const { ctx, app } = this;
    const data = await ctx.service.users.getUserByRole(ctx.request.query.id);
    this.success(data);
  }

  async login() {
    const { ctx, app, config } = this;
    const { nickname, code: js_code, avatarUrl: avatar_url } = ctx.request.body;
    const secret = '2ecfbf71dfde37f43dbc1bc3f0508e97';
    const appid = 'wx217dfb3d5f30e32e';
    const { data } = await this.ctx.curl('https://api.weixin.qq.com/sns/jscode2session', {
      method: 'GET',
      rejectUnauthorized: false,
      data: {
        appid, // 小程序的APPID
        secret, // 小程序的secret,
        js_code, // wx.login 登录成功后的code
      },
      dataType: 'json',
    });
    console.log('------看看data-------', data);
    console.log('------end-------');
    const user = await ctx.service.users.findByLogin(data.openid);
    console.log('------看看user-------', user);
    console.log('------end-------');
    const sign = userData => {
      console.log('------看看user.id-------', user.id);
      console.log('------end-------');
      const token = app.jwt.sign(
        {
          openid: userData.openid,
          user_id: user.id,
        },
        app.config.jwt.secret
      );
      const data = {
        ...user,
        token,
      };
      this.success(data);
    };
    if (user) {
      sign(user);
    } else {
      const newUser = await ctx.service.users.createUser({
        openid: data.openid,
        nickname,
        avatar_url,
      });
      console.log('------看看newUser-------', newUser);
      console.log('------end-------');
      sign(newUser);
    }
  }

  async testLogin() {
    const { ctx, app, config } = this;
    const token = app.jwt.sign(
      {
        openid: 'ov2nz6_UpSL4Xx6so2INkMw09mvU',
        user_id: 3,
      },
      app.config.jwt.secret
    );
    const data = {
      nickname: 'Lweilve',
      avatarUrl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
      token,
    };
    this.success(data);
  }

  async getUserByUserId() {
    const { ctx, app } = this;
    const data = await ctx.service.users.findByUserId(ctx.request.query.id);
    this.success(data);
  }

  async queryUserList() {
    const { ctx, app } = this;
    const userList = await ctx.service.users.queryUserList(ctx.request.body);
    this.success(userList);
  }

  async checkToken() {
    const { ctx, app } = this;
    ctx.body = { exp: ctx.state.user.exp };
  }

  async index() {
    const ctx = this.ctx;
    const query = {
      limit: toInt(ctx.query.limit),
      offset: toInt(ctx.query.offset),
    };
    ctx.body = await ctx.model.User.findAll(query);
  }

  async getUserByJSNumber() {
    const { ctx, app } = this;
    ctx.body = await ctx.model.User.findByJSNumber(ctx.request.query.js_number);
  }

  async createUser() {
    const { ctx, app } = this;
    ctx.validate(
      {
        nickname: "string",
        openid: "string",
        avatar_url: "string?",
      },
      ctx.request.body
    );
    const user = await ctx.service.users.createUser(ctx.request.body);
    this.success(user);
  }

  async updateUser() {
    // 修改用户信息
    const { ctx, app } = this;
    ctx.validate(
      {
        name: "string",
        js_number: { type: "string", min: 12, max: 12 },
        avatar: "string?",
        role: "array",
        class: "array",
      },
      ctx.request.body
    );
    const {
      id,
      name,
      js_number,
      avatar,
      role,
      class: classList,
    } = ctx.request.body;
    const user = await ctx.service.users.updateUserInfo(
      id,
      name,
      js_number,
      avatar,
      role,
      classList
    );
    this.success(user);
  }

  async destroy() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const user = await ctx.service.users.destroy(id);
    if (user === null) {
      // 抛出异常
      throw new NotFoundException("删除失败", 500);
    }
    this.success("删除成功");
  }
}

module.exports = UserController;
